<?php

namespace App\Admin\Actions\Grid;

use App\Models\Posts\WxPost;
use App\Models\Used\WxUsedComment;
use App\Models\Used\WxUsedGood;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UsedCommentsPassAction extends BatchAction
{
    /**
     * @return string
     */
	protected $title = '批量审核通过';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();
        foreach ($ids as $id){
            DB::transaction(function () use ($id){

                $used_comment = WxUsedComment::find($id);

                if(!in_array($used_comment->comment_state, [0, 2])){
                    return;
                }

                $uid = $used_comment->user_id;
                $comment_content = $used_comment->comment_content;
                $used_good_id = $used_comment->used_good_id;
                // 发送通知

                $msg = UserUtils::reward_user_coin($uid, 'used-comment');
                if($msg){
                    GatewayUtils::info_message(GatewayUtils::uid2client_id($uid), '恭喜，获得系统的发布留言：'.$msg);
                    UserUtils::assistant_notice($uid, '您发表的留言(id:<a href="/pagesU/used-mall/detail/index?id='.$used_good_id.'">'.$id.'</a>)已经审核通过，并获得留言奖励：'.$msg);
                }else{
                    UserUtils::assistant_notice($uid, '您发表的留言(id:<a href="/pagesU/used-mall/detail/index?id='.$used_good_id.'">'.$id.'</a>)已经审核通过');
                }
                WxUsedComment::where('id',$id)->update(['comment_state'=>1]);
            });

        }

        return $this->response()
            ->success('操作成功'.json_encode($this->getKey()))
            ->refresh();
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
		 return ['确认审核通过?'];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
